import { onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { message } from "@/utils/message";
import {
  getPickUpOrderCarListApi,
  delPickUpOrderCarApi
} from "@/api/pickUpOrderCarApi";

export function useOrderCar(deliveryOrderId) {
  const form = reactive({
    page: 1,
    perPage: 10,
    orderId: deliveryOrderId,
    entryType: 2
  });
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const indexMethod = (index: number) => {
    return index + 1;
  };
  const columns: TableColumnList = [
    {
      label: "ID",
      type: "index",
      index: indexMethod
    },
    {
      label: "车牌号",
      prop: "vehicleInfo.number"
    },
    {
      label: "状态",
      prop: "entryStatusStr"
    },
    {
      label: "开始时间",
      prop: "entryStartTime",
      minWidth: 100
    },
    {
      label: "结束时间",
      prop: "entryEndTime",
      minWidth: 100
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      minWidth: 100
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getPickUpOrderCarListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = 1;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getPickUpOrderCarListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = result.result.current_page;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getPickUpOrderCarListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.per_page;
    pagination.currentPage = result.current_page;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }
  onMounted(async () => {
    onSearch();
  });

  function handleDelete(row) {
    delPickUpOrderCarApi({ vehicleTimelineId: row.vehicleTimelineId }).then(
      () => {
        message(`删除成功`, { type: "success" });
        onSearch();
      }
    );
  }
  return {
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete
  };
}
